# -*- Coding = utf-8 -*-
# @time: 2021/1/29 9:53
# Author: YKL

import MySQLdb as mysql

no = int(input('编号:'))
name = input('名称:')
location = input('所在地:')
# 1.创建mysql数据库连接,获取连接对象
conn = mysql.connect(host='39.105.56.50', port=3306,
                     user='root', password='Yukl.911',
                     database='hrs', charset='utf8mb4',
                     connect_timeout=3)
try:
    # 2.基于连接对象创建游标对象
    with conn.cursor() as cursor:

        # 3.通过游标对象向数据库发出SQL语句,并获取执行结果
        affected_rows = cursor.execute(
            'insert into tb_dept values (%s, %s, %s)',
            (no, name, location)
        )
        if affected_rows == 1:
            print('新增部门成功')

        # 4.操作成功:通过连接对象执行提交操作(让之前的操作生效)
            conn.commit()
except mysql.MySQLError as err:
    print(err)
    # 操作失败:通过连接对象执行回滚操作(撤销之前的操作)
    conn.rollback()
finally:
    # 5.关闭连接,释放资源
    conn.close()
